{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "神经网络\n",
    "===============\n",
    "\n",
    "神经网络可以通过``torch.nn``包来创建。\n",
    "\n",
    "我们之前简单的了解了``autograd``，而``nn``会使用``autograd``来定义模型以及求梯度。\n",
    "一个``nn.Module``对象包括了许多网络层(layer)，并且有一个``forward(input)``方法来返回``output``。\n",
    "\n",
    "比如下图所示，我们会定义一个卷积网络来识别mnist图片\n",
    "\n",
    "![识别mnist的网络](mnist.png \"识别mnist的网络\")\n",
    "\n",
    "训练一个神经网络通常需要如下步骤：\n",
    "\n",
    "- 定义一个神经网络，它通常有一些可以训练的参数\n",
    "- 迭代一个数据集(dataset)\n",
    "- 处理给网络的输入\n",
    "- 计算loss(会调用Module对象的forward方法)\n",
    "- 计算loss对参数的梯度\n",
    "- 更新参数，通常使用如下的梯度下降方法来更新：\n",
    "  ``weight = weight - learning_rate * gradient``\n",
    "\n",
    "调用神经网络\n",
    "------------------\n",
    "让我们首先来定义网络：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Net(\n",
      "  (conv1): Conv2d(1, 6, kernel_size=(5, 5), stride=(1, 1))\n",
      "  (conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))\n",
      "  (fc1): Linear(in_features=400, out_features=120, bias=True)\n",
      "  (fc2): Linear(in_features=120, out_features=84, bias=True)\n",
      "  (fc3): Linear(in_features=84, out_features=10, bias=True)\n",
      ")\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "\n",
    "\n",
    "class Net(nn.Module):\n",
    "\n",
    "    def __init__(self):\n",
    "        super(Net, self).__init__()\n",
    "        # 输入是1个通道的灰度图，输出6个通道(feature map)，使用5x5的卷积核\n",
    "        self.conv1 = nn.Conv2d(1, 6, 5)\n",
    "        # 第二个卷积层也是5x5，有16个通道\n",
    "        self.conv2 = nn.Conv2d(6, 16, 5)\n",
    "        # 全连接层\n",
    "        self.fc1 = nn.Linear(16 * 5 * 5, 120)\n",
    "        self.fc2 = nn.Linear(120, 84)\n",
    "        self.fc3 = nn.Linear(84, 10)\n",
    "\n",
    "    def forward(self, x):\n",
    "        # 32x32 -> 28x28 -> 14x14 \n",
    "        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))\n",
    "        # 14x14 -> 10x10 -> 5x5\n",
    "        x = F.max_pool2d(F.relu(self.conv2(x)), 2)\n",
    "        x = x.view(-1, self.num_flat_features(x))\n",
    "        x = F.relu(self.fc1(x))\n",
    "        x = F.relu(self.fc2(x))\n",
    "        x = self.fc3(x)\n",
    "        return x\n",
    "\n",
    "    def num_flat_features(self, x):\n",
    "        size = x.size()[1:]  # 除了batch维度之外的其它维度。\n",
    "        num_features = 1\n",
    "        for s in size:\n",
    "            num_features *= s\n",
    "        return num_features\n",
    "\n",
    "\n",
    "net = Net()\n",
    "print(net)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "你只需要定义``forward``函数，而``backward``函数会自动通过``autograd``创建。\n",
    "在``forward``函数里我们可以使用任何处理Tensor的函数。\n",
    "\n",
    "可以使用函数``net.parameters()``来得到模型所有的参数。\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n",
      "torch.Size([6, 1, 5, 5])\n"
     ]
    }
   ],
   "source": [
    "params = list(net.parameters())\n",
    "print(len(params))\n",
    "print(params[0].size())  # conv1的weight"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "尝试一个随机的32x32的输入\n",
    "注意：这个网络(LeNet)期望的输入大小是32x32。如果使用MNIST数据集(28x28)，我们需要缩放到32x32。\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[ 0.1198,  0.0230,  0.0322, -0.0951,  0.1117,  0.0377, -0.0365, -0.1305,\n",
      "          0.1472,  0.0533]], grad_fn=<ThAddmmBackward>)\n"
     ]
    }
   ],
   "source": [
    "input = torch.randn(1, 1, 32, 32)\n",
    "out = net(input)\n",
    "print(out)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "默认的梯度会累加，因此我们通常在backward之前清除掉之前的梯度值：\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "net.zero_grad()\n",
    "out.backward(torch.randn(1, 10))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div class=\"alert alert-info\"><h4>注意</h4><p>``torch.nn``只支持mini-batches的输入。整个``torch.nn``\n",
    "    包的输入都必须第一维是batch，即使只有一个样本也要弄成batch是1的输入。\n",
    "    \n",
    "\n",
    "    <p>比如，``nn.Conv2d``的输入是一个4D的Tensor，shape是\n",
    "    ``nSamples x nChannels x Height x Width``。\n",
    "\n",
    "    如果你只有一个样本(nChannels x Height x Width)，那么可以使用``input.unsqueeze(0)``来增加一个batch维。</p></div>\n",
    "\n",
    "在继续学习之前，我们先简单的复习一下已经学过的一些类。\n",
    "\n",
    "\n",
    "**复习：**\n",
    "  -  ``torch.Tensor`` - 一个*多维数组*，在(依赖它的tensor)调用``backward()``时支持自动求导。它也会把计算得到的梯度保存起来。\n",
    "  -  ``nn.Module`` - 神经网络模块。可以方便的封装参数。\n",
    "  -  ``nn.Parameter`` - 一种特殊的Tensor，当我们把它作为Module的属性的时候，它会自动注册为这个模块的参数。、\n",
    "  -  ``autograd.Function`` - 实现了一个autograd operation的前向和后向定义。 每个``Tensor``的operation，都至少会创建一个``Function``节点， 它会和``Tensor``简历关联并且记录相关用于自动梯度计算需要的历史信息。\n",
    "\n",
    "**到目前位置，我们介绍了：**\n",
    "  -  定义神经网络\n",
    "  -  处理输入和进行前向计算，调用backward计算梯度。\n",
    "  \n",
    "**尚未介绍内容：**\n",
    "  -  计算loss\n",
    "  -  更新网络参数\n",
    "  \n",
    "损失函数\n",
    "-------------\n",
    "损失函数的参数是(output, target)对，output是模型的预测，target是实际的值。损失函数会计算预测值和真实值的差别，损失越小说明预测的越准。\n",
    "\n",
    "这里有许多不同的损失函数：\n",
    "`loss functions <http://pytorch.org/docs/nn.html#loss-functions>`\n",
    "\n",
    "最简单的一个损失函数是：``nn.MSELoss``，它会计算预测值和真实值的均方误差。\n",
    "\n",
    "比如：\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor(1.3318, grad_fn=<MseLossBackward>)\n"
     ]
    }
   ],
   "source": [
    "output = net(input)\n",
    "target = torch.randn(10)  # 随便伪造的一个“真实值” \n",
    "target = target.view(1, -1)  # 把它变成output的shape(1, 10) \n",
    "criterion = nn.MSELoss()\n",
    "\n",
    "loss = criterion(output, target)\n",
    "print(loss)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果从``loss``往回走，需要使用tensor的``.grad_fn``属性，我们Negative看到这样的计算图：\n",
    "\n",
    "\n",
    "::\n",
    "\n",
    "    input -> conv2d -> relu -> maxpool2d -> conv2d -> relu -> maxpool2d\n",
    "          -> view -> linear -> relu -> linear -> relu -> linear\n",
    "          -> MSELoss\n",
    "          -> loss\n",
    "\n",
    "因此当调用``loss.backward()``时，PyTorch会计算这个图中所有``requires_grad=True``的tensor关于loss的梯度。\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<MseLossBackward object at 0x7fbd626f8fd0>\n",
      "<ThAddmmBackward object at 0x7fbd626f82e8>\n",
      "<ExpandBackward object at 0x7fbd626f8fd0>\n"
     ]
    }
   ],
   "source": [
    "print(loss.grad_fn)  # MSELoss\n",
    "print(loss.grad_fn.next_functions[0][0])  # Add\n",
    "print(loss.grad_fn.next_functions[0][0].next_functions[0][0])  # Expand"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "反向梯度计算\n",
    "--------\n",
    "在调用``loss.backward()``之前，我们需要清除掉tensor里之前的梯度，否则会累加进去。\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "conv1.bias.grad before backward\n",
      "tensor([0., 0., 0., 0., 0., 0.])\n",
      "conv1.bias.grad after backward\n",
      "tensor([-0.0035, -0.0056, -0.0081,  0.0094, -0.0202,  0.0192])\n"
     ]
    }
   ],
   "source": [
    "net.zero_grad()     # 清掉tensor里缓存的梯度值。\n",
    "\n",
    "print('conv1.bias.grad before backward')\n",
    "print(net.conv1.bias.grad)\n",
    "\n",
    "loss.backward()\n",
    "\n",
    "print('conv1.bias.grad after backward')\n",
    "print(net.conv1.bias.grad)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来我们来看怎么使用损失函数。\n",
    "\n",
    "**深入阅读：**\n",
    "\n",
    "  torch.nn包括了很多模块和损失函数，这是深度神经网络的基础。完整的文档在`这里 <http://pytorch.org/docs/nn>`\n",
    "\n",
    "**最后需要介绍的内容：**\n",
    "\n",
    "  - 更新神经网络的参数。\n",
    "  \n",
    "更新参数\n",
    "------------------\n",
    "更新参数最简单的方法是使用随机梯度下降(SGD)：\n",
    "\n",
    "     ``weight = weight - learning_rate * gradient``\n",
    "\n",
    "我们可以使用如下简单的代码来实现更新：\n",
    "\n",
    ".. code:: python\n",
    "\n",
    "    learning_rate = 0.01\n",
    "    for f in net.parameters():\n",
    "        f.data.sub_(f.grad.data * learning_rate)\n",
    "\n",
    "通常我们会使用更加复杂的更新方法，比如SGD, Nesterov-SGD, Adam, RMSProp等等。\n",
    "为了实现这些算法，我们可以使用``torch.optim``包，它的用法也非常简单：\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.optim as optim\n",
    "\n",
    "# 创建optimizer，需要传入参数和learning rate\n",
    "optimizer = optim.SGD(net.parameters(), lr=0.01)\n",
    "\n",
    "# 清除梯度\n",
    "optimizer.zero_grad()  \n",
    "output = net(input)\n",
    "loss = criterion(output, target)\n",
    "loss.backward()\n",
    "optimizer.step()    # optimizer会自动帮我们更新参数"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    ".. 注意::\n",
    "\n",
    "      即使使用optimizer，我们也需要清零梯度。我们不需要一个个的清除，只需要用\n",
    "      ``optimizer.zero_grad()``。\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py3.6-env",
   "language": "python",
   "name": "py3.6-env"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
